package link_list;

import link_list.node.SinglyListNode;

/**
 * 单向链表反转
 */

public class SinglyLinkedList {

    public static SinglyListNode reverseList(SinglyListNode first){
        SinglyListNode pre = null,post;
        SinglyListNode curr= first;
        if(first == null){
            return null;
        }
        while(curr!=null){
            post = curr.next;
            curr.next = pre;
            pre = curr;
            curr = post;

        }
        return pre;
    }
    public static SinglyListNode reverseListRecursion(SinglyListNode first){
        if(first == null || first.next == null){
            return first;
        }
        SinglyListNode resultList = reverseListRecursion(first.next);
        first.next.next = first;
        first.next = null;

        return resultList;
    }

    public static void main(String[] args) {
        SinglyListNode first = new SinglyListNode(3);
        first.next=new SinglyListNode(2);
        first.next.next=new SinglyListNode(1);
        SinglyListNode result = reverseList(first);
        while (result !=null){
            System.out.print(result.val);
            result = result.next;
        }

        System.out.println("");

        SinglyListNode first2 = new SinglyListNode(8);
        first2.next=new SinglyListNode(6);
        first2.next.next=new SinglyListNode(3);
        first2.next.next.next=new SinglyListNode(2);
        SinglyListNode result2 = reverseListRecursion(first2);
        while (result2 !=null){
            System.out.print(result2.val);
            result2 = result2.next;
        }
    }
}
